//MC8635模块
#include "mc8635.h"
#include "format.h"
#include "pc_ajr.h"
#include "main.h"

u8 MC8635_RevTime, MC8635_IRQBuf[1024];
u8 MC8635_SendBufPtr, MC8635_SendBuf[512];
u16 MC8635_IRQBufPtr, MC8635_RecBufPtr, MC8635_SendLen;

u8 MC8635_RecState, MC8635_ReadBuf[1024*2], MC8635_TXTBuf[200];
u8 MC8635_WorkFig, MC8635_WorkErr, MC8635_ComWait;
u16 MC8635_WorkTimeout;

void MC8635_Usart_Init(void)
{
	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	
	//USART3 中断
	NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;	//抢占优先级=2
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	//属性
	USART_InitStructure.USART_BaudRate = 115200;
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity = USART_Parity_No;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	USART_Init(USART3, &USART_InitStructure);
	//相关变量
	MC8635_IRQBufPtr = 0;
	MC8635_RevTime = 0;
	
	MC8635_RecBufPtr = 0;
	MC8635_RecState = 0;
	
	MC8635_SendBufPtr = 0;
	MC8635_SendLen = 0;
	
	MC8635_WorkFig = 0xE0;
	MC8635_WorkTimeout = 0;
	MC8635_WorkErr = 0;
	//
	//开接收与发送完成中断
	USART_ITConfig(USART3, USART_IT_TC, ENABLE);
	USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
	USART3->SR &= ~(USART_FLAG_TC|USART_FLAG_RXNE); 	//清中断
	USART_Cmd(USART3, ENABLE);
}

void USART3_IRQHandler(void)
{
	unsigned int IIR;
	char tmp = 0;

	IIR = USART3->SR;
	
	if (IIR & USART_FLAG_TC)     //发送中断
	{  
		USART3->SR &= ~USART_FLAG_TC; //清中断
		if(MC8635_SendBufPtr < MC8635_SendLen)
		{
			USART3->DR = (MC8635_SendBuf[MC8635_SendBufPtr++] & 0x1FF);
		}
		else
		{
			MC8635_SendLen = 0;
			MC8635_SendBufPtr = 0;
		}
	}
  
	if (IIR & USART_FLAG_RXNE)      //读中断
	{             
		USART3->SR &= ~USART_FLAG_RXNE; //清除中断
		tmp = (USART3->DR & 0x1FF);		//取数据
		if(MC8635_IRQBufPtr < 1020)
		{	
			MC8635_IRQBuf[MC8635_IRQBufPtr++] = tmp;	
		}
		MC8635_RevTime = 5;
	}
}

////硬件开关机
//void MC8635_ON_OFF(void)
//{
//	IWDG_ReloadCounter();
//	GPIO_SetBits(GPIOC, GPIO_Pin_12);
//	delay_ms(1500);
//	IWDG_ReloadCounter();
//	delay_ms(1500);
//	IWDG_ReloadCounter();
//	GPIO_ResetBits(GPIOC, GPIO_Pin_12);
//	delay_ms(1000);
//	IWDG_ReloadCounter();
//}
//硬件复位
void MC8635_RESET(void)
{
	IWDG_ReloadCounter();
	GPIO_SetBits(GPIOD, GPIO_Pin_0);
	delay_ms(200);
	IWDG_ReloadCounter();
	GPIO_ResetBits(GPIOD, GPIO_Pin_0);
}
//AT发送
void MC8635_send_AT(u8 dlen)
{
	MC8635_SendLen = dlen;
	MC8635_SendBufPtr = 1;
	USART_SendData(USART3, MC8635_SendBuf[0]);
}

void Task_MC8635_Manage(void)
{
	u8 tmp, data_len;
	u16 i, data_start, data_end;
	s16  ret;
	
	switch(MC8635_WorkFig)
	{
		case 0xE0:   //模块上电
		{
			MC8635_WorkFig = 0xE5;
			MC8635_ComWait = 50;	//5s
		#if DEBUG > 0
			printf("Wait:Pw_On\r\n");
		#endif
		}
		break;
		case 0xE1:   //等待模块开机输出(17B)
		{
			if(MC8635_RecState == 'n')
			{
			#if DEBUG > 0
				printf("rlen(%d):%s\r\n", MC8635_RecBufPtr, MC8635_ReadBuf);
//				printf("rlen(%d):", MC8635_RecBufPtr);
//				for(i=0;i<MC8635_RecBufPtr;i++)
//				{
//					printf("%02X", MC8635_ReadBuf[i]);
//				}
//				printf("\r\n");
			#endif
				if((memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-13], "+ZIND: ME\r\n\r\n", 13) == 0) || 
					(memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-13], "+ZIND: ME\r\n", 11) == 0))
				{
					MC8635_WorkFig = 0;
					MC8635_WorkTimeout = 100;	//10s
				#if DEBUG > 0
					printf("Wait:Pw_SIM\r\n");
				#endif
				}
				else
				{
				#if DEBUG > 0
					printf("Recv but not ZIND\r\n");
				#endif
				}
				MC8635_RecState = 0;
			}
		}
		break;
		case 0xE2:   //模块硬件开机
		{
			IWDG_ReloadCounter();
			GPIO_SetBits(GPIOC, GPIO_Pin_12);
			MC8635_WorkFig = 0xF0;
			MC8635_WorkTimeout = 30;	//3s
		#if DEBUG > 0
			printf("DO:ON/OFF\r\n");
		#endif
		}
		break;
		case 0xE3:   //模块硬件复位
		{
			MC8635_RESET();
			MC8635_WorkFig = 0xE1;
			MC8635_WorkTimeout = 150;	//15s
			MC8635_WorkErr = 0;
		#if DEBUG > 0
			printf("DO:ReSet\r\n");
		#endif
		}
		break;
		case 0xE4:   //模块软关机  AT+ZPWROFF
		{
			memcpy(MC8635_SendBuf, "AT+ZPWROFF\r", 11);
			MC8635_send_AT(11);
			MC8635_WorkFig = 0xE1;
			MC8635_WorkTimeout = 50;	//5s
			MC8635_WorkErr = 0;
		#if DEBUG > 0
			printf("send:ZPWROFF\r\n");
		#endif
		}
		break;
		case 0xE5:   //模块软复位  AT^RESET
		{
			if(MC8635_ComWait != 0)
			{
				MC8635_ComWait--;
			}
			else
			{
				memcpy(MC8635_SendBuf, "AT^RESET\r", 9);
				MC8635_send_AT(9);
				MC8635_WorkFig = 0xE1;
				MC8635_WorkTimeout = 100;	//10s
				MC8635_WorkErr = 0;
			#if DEBUG > 0
				printf("send:RESET\r\n");
			#endif
			}
		}
		break;
		case 0x00:   //判断SIM卡(13B)	^SIMST: 1
		{
			if(MC8635_RecState == 'n')
			{
			#if DEBUG > 0
				printf("rlen(%d):%s\r\n", MC8635_RecBufPtr, MC8635_ReadBuf);
//				printf("rlen(%d):", MC8635_RecBufPtr);
//				for(i=0;i<MC8635_RecBufPtr;i++)
//				{
//					printf("%02X", MC8635_ReadBuf[i]);
//				}
//				printf("\r\n");
			#endif
				if( (memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-11], "^SIMST: 1\r\n", 11) == 0) || 
					  (memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-13], "^SIMST: 1\r\n\r\n", 13) == 0))
				{
					MC8635_WorkFig = 1;
					MC8635_WorkErr = 0;
					MC8635_WorkTimeout = 0;
				}
				MC8635_RecState = 0;
			}
		}
		break;
		case 0x01:   //确认模块（关回显）  ATE0
		{
		#if DEBUG > 0
			printf("send:ATE\r\n");
		#endif
			memcpy(MC8635_SendBuf, "ATE0\r", 5);
			MC8635_send_AT(5);
			MC8635_WorkFig++;
			MC8635_WorkTimeout = 10;	//1s
		}
		break;
		case 0x02:   //关回显应答
		{
			if(MC8635_RecState == 'n')
			{
				if(memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-4], "OK\r\n", 4) == 0)
				{
					MC8635_WorkFig = 3;
					MC8635_WorkErr = 0;
					MC8635_WorkTimeout = 0;
					MC8635_ComWait = 10;
				}
				MC8635_RecState = 0;
			}
		}
		break;
		case 0x03:   //建立无线连接  AT^IPCALL=1,"test","test"
		{
			if(MC8635_ComWait != 0)
			{
				MC8635_ComWait--;
			}
			else
			{
			#if DEBUG > 0
				printf("send:IPCALL 1\r\n");
			#endif
				memcpy(MC8635_SendBuf, "AT^IPCALL=1,\"test\",\"test\"\r", 26);
				MC8635_send_AT(26);
				MC8635_WorkFig++;
				MC8635_WorkTimeout = 150;	//15s
			}
		}
		break;
		case 0x04:   //建立无线连接应答
		{
			if(MC8635_RecState == 'n')
			{
			#if DEBUG > 0
				printf("rlen(%d):%s\r\n", MC8635_RecBufPtr, MC8635_ReadBuf);
			#endif
				if((memcmp(MC8635_ReadBuf, "\r\n^IPCALL:", 10)==0)&&(MC8635_RecBufPtr > 20))
				{
					//联网成功
					MC8635_WorkFig = 5;
					MC8635_WorkErr = 0;
					MC8635_WorkTimeout = 0;
					MC8635_ComWait = 20;
				}
				else if(memcmp(MC8635_ReadBuf, "\r\n^IPCALL: 0\r\n", 14)==0)
				{
					//联网失败
					if(MC8635_WorkErr < 20)
					{
						MC8635_WorkErr++;
						MC8635_WorkFig = 3;
						MC8635_WorkTimeout = 0;
						MC8635_ComWait = 50; //5s
					}
				}
				MC8635_RecState = 0;
			}
		}
		break;
		case 0x05:   //连接远端服务器  AT^IPOPEN=4,6500,"120.26.216.47",8888,1
		{
			if(MC8635_ComWait != 0)
			{
				MC8635_ComWait--;
			}
			else
			{
			#if DEBUG > 0
				printf("send:IPOPEN\r\n");
			#endif
				memcpy(MC8635_SendBuf, "AT^IPOPEN=4,6500,\"120.26.88.40\",8888,1\r", 40);
				MC8635_send_AT(40);
				MC8635_WorkFig++;
				MC8635_WorkTimeout = 30;	//3s
			}
		}
		break;
		case 0x06:   //连接远端服务器应答
		{
			if(MC8635_RecState == 'n')
			{
				if(memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-4], "OK\r\n", 4) == 0)
				{
					MC8635_WorkFig = 0x10;
					MC8635_WorkErr = 0;
					MC8635_WorkTimeout = 0;
				}
				MC8635_RecState = 0;
			}
		}
		break;
		case 0x07:   //断开无线连接  AT^IPCALL=0
		{
		#if DEBUG > 0
			printf("send:IPCALL 0\r\n");
		#endif
			memcpy(MC8635_SendBuf, "AT^IPCALL=0\r", 12);
			MC8635_send_AT(12);
			MC8635_WorkFig++;
			MC8635_WorkTimeout = 30;	//3s
		}
		break;
		case 0x08:   //断开连接应答
		{
			if(MC8635_RecState == 'n')
			{
				if(memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-4], "OK\r\n", 4) == 0)
				{
					MC8635_WorkFig = 3;
					MC8635_WorkErr = 0;
					MC8635_WorkTimeout = 0;
					MC8635_ComWait = 30;
				}
				MC8635_RecState = 0;
			}
		}
		break;
		case 0x10:   //联网：发送、接收
		{
			if(MC8635_RecState == 'n')
			{
				#if DEBUG > 0
					printf("rlen(%d):%s\r\n", MC8635_RecBufPtr, MC8635_ReadBuf);
				#endif
				//Buzzer_timers_add(1);
				//对于模块自动上传的状态进行处理
				if(memcmp(MC8635_ReadBuf, "\r\n^IPCALL: 0\r\n", 14) == 0)
				{ //模块自动断开无线连接
					MC8635_WorkFig = 3;
					MC8635_ComWait = 30;
					MC8635_RecState = 0;
				}
				else if(memcmp(MC8635_ReadBuf, "\r\n^IPSTAT: 4,1", 14) == 0)
				{ //模块自动断开Socket
					MC8635_WorkFig = 7;
					MC8635_RecState = 0;
				}
				else if(memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-2], "\r\n", 2) != 0)
				{ //未接收完全
					MC8635_RecState = 'Y';
				#if DEBUG > 0
					printf("read:Continue!\r\n");
				#endif
				}
				else
				{
					data_start = 0;
					data_end = 0;
					memset(MC8635_TXTBuf, 0, 200);
					while((MC8635_RecBufPtr - data_end) > 85)
					{
						//查找 ^IPRECV: 后面从第4个0x2C开始到0x0D0A的都是数据
						for(i=data_end;i<MC8635_RecBufPtr-10;i++)
						{
							if(memcmp(&MC8635_ReadBuf[i], "IPRECV:", 7) == 0)
							{
								#if DEBUG > 0
									printf("read:IPRECV\r\n");
								#endif
								break;
							}
						}
						if(i<MC8635_RecBufPtr-10)
						{
							for(tmp=0;i<MC8635_RecBufPtr-3;i++)
							{
								if(MC8635_ReadBuf[i] == 0x2C)
								{
									tmp++;
									if(tmp >= 4)
									{
										data_start = i+1;
										#if DEBUG > 0
											printf("read:start(%d)\r\n", data_start);
										#endif
										break;
									}
								}
							}
							
							if(i<MC8635_RecBufPtr-3)
							{
								for(;i<=MC8635_RecBufPtr-2;i++)
								{
									if(memcmp(&MC8635_ReadBuf[i], "\r\n", 2) == 0)
									{
										data_end = i;
										#if DEBUG > 0
											printf("read:end(%d)\r\n", data_end);
										#endif
										break;
									}
								}
								
								if(i<=MC8635_RecBufPtr-2)
								{
									//校验长度
									if((((data_end-data_start)%2) != 0)||((data_end-data_start)<64))
									{
										;
									}
									else
									{
										data_len = (data_end-data_start)/2;
										if(data_len > 200)
										{
											data_len = 200;
										}
										//接收到数据，转化为Hex格式
										for(i=0;i<data_len;i++)
										{
											ret = Ascii2_Hex(&MC8635_ReadBuf[data_start+2*i]);
											if(ret == -1)
											{
												break;
											}
											MC8635_TXTBuf[i] = (u8)ret;
										}
										if(i >= data_len)
										{
										#if DEBUG > 0
											printf("data:%s\r\n", &MC8635_ReadBuf[data_start]);
										#endif
											MC8635_WorkErr = 0;
											////////////////////
											PCRevFunTask(MC8635_TXTBuf, data_len); //对数据进行协议处理
											//Buzzer_timers_add(1);
											////////////////////
										}
										else
										{
											break;
										}
									}
								}
								else
								{
									data_end = MC8635_RecBufPtr;
									break;
								}
							}
							else
							{
								data_end = MC8635_RecBufPtr;
								break;
							}
						}
						else
						{
							data_end = MC8635_RecBufPtr;
							break;
						}
					}
					MC8635_RecState = 0;
				}
			}
			//
			if(PC_Send_OK == 0)
			{
				UDP_Main();
			}
			if(PC_Send_OK == 'Y')
			{
				PC_Send_OK = 0;
			#if DEBUG > 0
				printf("send:IPSEND(%d)\r\n", PC_SendLen);
			#endif
				memcpy(MC8635_SendBuf, "AT^IPSEND=4,\"", 13);
				//将发送的数据，转化为ASCII格式
				for(i=0;i<PC_SendLen;i++)
				{
					Hex_Ascii2(PC_SendBuf[i], &MC8635_SendBuf[13+2*i]);
				}
				memcpy(&MC8635_SendBuf[13+2*PC_SendLen], "\"\r", 2);
				MC8635_send_AT(15+2*PC_SendLen);
				MC8635_WorkFig = 0x12;
				MC8635_WorkTimeout = 50;	//5s
			}
		}
		break;
		case 0x12:	//IPSEND应答
		{
			if(MC8635_RecState == 'n')
			{
				#if DEBUG > 0
					printf("rlen(%d):%s\r\n", MC8635_RecBufPtr, MC8635_ReadBuf);
				#endif
				if((memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-4], "OK\r\n", 4) == 0) ||
					(memcmp(&MC8635_ReadBuf[MC8635_RecBufPtr-6], "OK\r\n\r\n", 6) == 0) ||
					(memcmp(MC8635_ReadBuf, "\r\n^DSDORMANT: 0\r\n", 17) == 0) ||
					(memcmp(MC8635_ReadBuf, "\r\n^IPSEND:", 10) == 0))
				{ //发送成功
					MC8635_WorkFig = 0x10;
					MC8635_WorkErr = 0;
					MC8635_WorkTimeout = 0;
				}
				else if((memcmp(MC8635_ReadBuf, "\r\n+CME ERROR:", 13) == 0) || 
						(memcmp(MC8635_ReadBuf, "\r\nERROR\r\n", 9) == 0))
				{ //发送出错
					MC8635_WorkFig = 7;
				}
				else if(memcmp(MC8635_ReadBuf, "\r\n^IPRECV:", 10) == 0)
				{
					//直接接收到服务器应答数据了，不要清除标志位~~
					MC8635_WorkFig = 0x10;
					MC8635_WorkErr = 0;
					MC8635_WorkTimeout = 0;
					return;
				}
				MC8635_RecState = 0;
			}
		}
		break;
		default:
		{
		}
		break;
	}
}

void Task_MC8635_Time(void)		//100ms单位
{
	if(MC8635_WorkTimeout != 0)
	{
		MC8635_WorkTimeout--;
		if(MC8635_WorkTimeout == 0)
		{
			switch(MC8635_WorkFig)
			{
				case 0xE1:   //等待模块开机输出
				{
					if(MC8635_WorkErr < 100)
					{
						MC8635_WorkErr++;
					}
					MC8635_WorkFig = 0xE2;
				#if DEBUG > 0
					printf("TimeOut, fig(E1H)=0x%02X\r\n", MC8635_WorkFig);
				#endif
				}
				break;
				case 0xF0:   //模块硬件开机(3s)
				{
					GPIO_ResetBits(GPIOC, GPIO_Pin_12);
					MC8635_WorkFig = 0xE1;
					if(MC8635_WorkErr > 3)
					{
						MC8635_WorkTimeout = 300;	//30s
					}
					else
					{
						MC8635_WorkTimeout = 100;	//10s
					}
				}
				break;
				case 0x00:   //等待判断SIM卡
				{
					MC8635_WorkFig = 0xE5;
				}
				break;
				case 0x02:   //关回显应答
				{
					MC8635_WorkErr++;
					if(MC8635_WorkErr >= 3)
					{
						MC8635_WorkFig = 0xE5;
					}
					else
					{
						MC8635_WorkFig = 0x01;
					}
				}
				break;
				case 0x04:   //建立无线连接应答
				{
					MC8635_WorkErr++;
					if(MC8635_WorkErr >= 3)
					{
						MC8635_WorkFig = 0xE5;
					}
					else
					{
						MC8635_WorkFig = 0x03;
					}
				}
				break;
				case 0x06:   //连接远端服务器应答
				{
					MC8635_WorkErr++;
					if(MC8635_WorkErr >= 3)
					{
						MC8635_WorkFig = 0xE5;
					}
					else
					{
						MC8635_WorkFig = 0x05;
					}
				}
				break;
				case 0x08: 
				{
					MC8635_WorkErr++;
					if(MC8635_WorkErr >= 3)
					{
						MC8635_WorkFig = 0xE5;
					}
					else
					{
						MC8635_WorkFig = 0x07;
					}
				}
				break;
				case 0x12: 
				{
					MC8635_WorkErr++;
					if(MC8635_WorkErr >= 3)
					{
						MC8635_WorkFig = 0xE5;
					}
					else
					{
						MC8635_WorkFig = 0x10;
					}
				#if DEBUG > 0
					printf("TimeOut, fig(12H)=0x%02X\r\n", MC8635_WorkFig);
				#endif
				}
				break;
				default:
				{
				}
				break;
			}
		}
	}
}
